<template>
  <div class="results">
    <!-- 顶部导航 -->
    <van-nav-bar
      :title="this.key + '搜索结果'"
      left-arrow
      @click-left="$router.back()"
    >
    </van-nav-bar>
    <!-- list列表 -->
    <van-pull-refresh v-model="refreshing" @refresh="onRefresh">
      <van-list
        v-model="loading"
        :finished="finished"
        finished-text="没有更多了"
        @load="onLoad"
      >
        <van-cell v-for="(item, index) in list" :key="index">
          <template #title>
            <div>{{ item.title }}</div>
          </template>
        </van-cell>
      </van-list>
    </van-pull-refresh>
  </div>
</template>

<script>
import { getSearchApi } from '@/api'
export default {
  data () {
    return {
      key: this.$route.query.key,
      refreshing: false,
      finished: false,
      loading: false,
      page: 1,
      per_page: 10,
      total_count: '',
      list: []
    }
  },
  methods: {
    onRefresh () {
      // 清空数据源
      this.list = []
      this.finished = false
      this.refreshing = false
      this.loading = true
      this.page = 1
      this.onLoad()
    },
    async onLoad () {
      // 调用接口获取搜索结果数据
      const res = await getSearchApi({
        page: this.page, // 当前页
        per_page: this.per_page, // 当前页容量
        q: this.key
      })
      console.log(res)
      //   保存数据到List
      //   this.list = res.data.data.results 需要将数据展开
      this.list = [...this.list, ...res.data.data.results]
      this.page = res.data.data.page
      this.per_page = res.data.data.per_page
      //   将page当前页+1
      this.page++
      // 执行完函数会自动将loading值改为true需手动将loading 改为false
      this.loading = false
      //   判断数据源是否加载完毕
      if (res.data.data.results.length === 0) {
        this.finished = true
      }
    }
  }
}
</script>

<style></style>
